package com.gyy.faq.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {
	private List<String> passList = new ArrayList();

	public LoginInterceptor() {
		passList.add(".*/public/login(\\.json)?");
		passList.add(".*/public/logout(\\.json)?");
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

		String uri = request.getRequestURI();
		for (String pattern : passList) {
			if (uri.matches(pattern)) {
				return true;
			}
		}
		if (request.getRequestURI().indexOf("/rankloc/rank/dist") != -1) {
			if (request.getSession().getAttribute("uid") == null) {
				response.sendRedirect("/faq/help/index.html");
				return false;
			}
			if (request.getSession().getAttribute("uid") != null) {
				return true;
			}
			response.sendRedirect("/faq/help/index.html");
			return false;
		}
		if (request.getRequestURI().equals("/faq") || request.getRequestURI().equals("/faq/")) {
			if (request.getSession().getAttribute("uid") == null) {
				response.sendRedirect("/faq/help/index.html");
				return false;
			}
			if (request.getSession().getAttribute("uid") != null) {
				return true;
			}
			response.sendRedirect("/faq/help/index.html");
			return false;
		}
		if (request.getRequestURI().equals("/error") || request.getRequestURI().equals("/error/")) {
			if (request.getSession().getAttribute("uid") == null) {
				response.sendRedirect("/faq/help/index.html");
				return false;
			}
			if (request.getSession().getAttribute("uid") != null) {
				return true;
			}
			response.sendRedirect("/faq/help/index.html");
			return false;
		}

		return true;
	}

	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

	}
}
